<template>
  <BasicModal :title="title" :width="800" v-bind="$attrs" @ok="handleOk" @register="registerModal">
    <BasicForm @register="registerForm">
      <template #reply="{ model, field }">
        <a-form-item-rest>
          <WxReply v-model:obj-data="dataModel" />
        </a-form-item-rest>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { computed, ref, unref } from "vue"
  import WxReply from "/@/views/channel/wxMp/components/WxReply/index.vue"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { BasicModal, useModalInner } from "/@/components/Modal"

  import { subscribeReplyFormSchema, MpAutoReplyTypeEnum } from "./data"
  import { useConvert } from "./convert"
  import { saveOrUpdateMpAutoReply } from "./api"

  const emit = defineEmits(["success", "register"])
  const props = defineProps({
    objData: {
      type: Object,
      required: false,
    },
  })
  const dataModel = ref<any>({ type: "text" })
  // 当前是否是更新模式
  const isUpdate = ref<boolean>(false)
  const title = computed(() => (isUpdate.value ? "编辑自动回复" : "新增自动回复"))

  //注册表单
  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    schemas: subscribeReplyFormSchema,
    showResetButton: false,
    showSubmitButton: false,
    showActionButtonGroup: false,
  })

  // 注册弹窗
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields()
    isUpdate.value = unref(data?.isUpdate)
    let record = unref(data?.record)
    if (typeof record !== "object") {
      record = {}
    }
    dataModel.value = useConvert.toWxReply(record)
    if (!isUpdate.value) {
      dataModel.value.type = "text"
    }
    await setFieldsValue({ ...record })
  })

  // 提交事件
  async function handleOk() {
    try {
      setModalProps({ confirmLoading: true })
      let values = await validate()
      const form = { ...values }
      const obj = dataModel.value
      form.type = MpAutoReplyTypeEnum.SUBSCRIBE
      form.responseMessageType = obj.type
      form.responseContent = obj.content
      form.responseMediaId = obj.mediaId
      form.responseMediaUrl = obj.url
      form.responseTitle = obj.title
      form.responseDescription = obj.description
      form.responseThumbMediaId = obj.thumbMediaId
      form.responseThumbMediaUrl = obj.thumbMediaUrl
      form.responseArticles = obj.articles
      form.responseMusicUrl = obj.musicUrl
      form.responseHqMusicUrl = obj.hqMusicUrl

      console.log("form: ", form)

      //提交表单
      await saveOrUpdateMpAutoReply(form, isUpdate.value)
      //关闭弹窗
      closeModal()
      //刷新列表
      emit("success")
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }
</script>
